<template>
    <div class="common-layout">
    <el-container>
      <!--头部部分--> 
      <el-header>
          <el-row justify="space-between" align="middle">
            <el-col :span="6">
              <div class="breadcrumb">
                <el-icon><Fold /></el-icon>
                <span>首页</span>
                <span>/</span>
                <span>运营</span>
                <span>/</span>
                <span class="current">设备公告</span>
              </div>
            </el-col>
            <el-col :span="3">
              <div class="user-info">
                <el-avatar :size="30" src="" />
                <span class="username">admin</span>
              </div>
            </el-col>
          </el-row>
      </el-header>
      <!--选项-->
      <el-main class="option">
        <el-button 
          size="small" 
          :class="{ 'is-active': activeButton === 'home' }"
          @click="setActiveButton('home')"
        >首页</el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'theme' }"
          @click="setActiveButton('theme')"
        >主题设置
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'video' }"
          @click="setActiveButton('video')"
        >视频
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'screen' }"
          @click="setActiveButton('screen')"
        >大屏配置
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'device' }"
          @click="setActiveButton('device')"
        >设备公告
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'voucher' }"
          @click="setActiveButton('voucher')"
        >代金券核销
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'service' }"
          @click="setActiveButton('service')"
        >服务商订单
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'agent' }"
          @click="setActiveButton('agent')"
        >代理商订单
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'holder' }"
          @click="setActiveButton('holder')"
        >设备持有人订单
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'statistics' }"
          @click="setActiveButton('statistics')"
        >设备统计
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'balance' }"
          @click="setActiveButton('balance')"
        >余额对账
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'wechat' }"
          @click="setActiveButton('wechat')"
        >微信打款失败列表
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'withdraw' }"
          @click="setActiveButton('withdraw')"
        >持有人提现统计
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'account' }"
          @click="setActiveButton('account')"
        >账户流水
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'reward' }"
          @click="setActiveButton('reward')"
        >奖励设置
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'org' }"
          @click="setActiveButton('org')"
        >组织机构
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'version' }"
          @click="setActiveButton('version')"
        >版本设置
            <el-icon><CloseBold /></el-icon>
        </el-button>
        <el-button 
          size="small"
          :class="{ 'is-active': activeButton === 'admin' }"
          @click="setActiveButton('admin')"
        >管理员
            <el-icon><CloseBold /></el-icon>
        </el-button>

      </el-main>
      <!--内容部分-->
      <el-main class="content">
          <el-header class="content-header">
            <!--添加-->
            <el-button type="danger" class="add" @click="add">
              <el-icon><Plus /></el-icon>
              添加
            </el-button>
            <!--刷新-->
            <el-button type="info" class="refresh" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>           
              刷新
            </el-button>
          </el-header>
          <!--数据表格-->
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="title" label="标题" width="15%" ></el-table-column>
            <el-table-column label="图片" width="15%" >
              <template #default="scope">
                <el-image 
                      v-if="scope.row.image" 
                      :src="`${scope.row.image}`" 
                      style="width: 40px; height: 40px"
                      fit="cover"
                      fallback="https://via.placeholder.com/40x40?text=加载失败"
                    />
                <span v-else class="no-image">无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="deviceAvailable" label="设备是否可用" width="8%" >
              <template #default="scope">
                {{ scope.row.deviceAvailable === 1 ? '可用' : '不可用' }}
              </template>
            </el-table-column>
            <el-table-column prop="displayTime" label="显示时间" width="20%" >
              <template #default="scope">
                {{ scope.row.time ? scope.row.time.split(',').join(' 至 ') : '无' }}
              </template>
            </el-table-column>
            <el-table-column prop="isDisplay" label="是否显示" width="8%" >
              <template #default="scope">
                {{ scope.row.isDisplay === 1 ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="添加日期" width="20%" ></el-table-column>
            <el-table-column label="操作" width="12%" >
              <template #default="scope">
                <el-button 
                  class="edit"
                  size="small" 
                  type="primary" 
                  @click="handleEdit(scope.$index)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
              </template>
            </el-table-column>
          
          </el-table>
                
      </el-main>
    </el-container>
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="图片">
           <el-upload
              class="avatar-uploader"
              action="http://106.13.143.56:8080/garbageSys/commit/uploadImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
            >
             
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="无法加载" />
              <div v-else class="avatar-uploader-icon">
                <el-icon><Plus /></el-icon>
                <p>点击上传</p>
              </div>
            </el-upload>
        </el-form-item>
        
        <el-form-item label="设备是否可用" prop="deviceAvailable">
          <el-radio-group v-model="form.deviceAvailable">
            <el-radio label="可用">可用</el-radio>
            <el-radio label="不可用">不可用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="显示时间" prop="displayTime">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="应用设备" prop="deviceScope">
          <el-radio-group v-model="form.deviceScope">
            <el-radio label="全部设备">全部设备</el-radio>
            <el-radio label="应用部分设备">应用部分设备</el-radio>
            <el-radio label="屏蔽部分设备">屏蔽部分设备</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否显示" prop="isDisplay">
          <el-radio-group v-model="form.isDisplay">
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Fold, Plus, Refresh, Edit, CloseBold } from '@element-plus/icons-vue'
import { getDeviceNotice, addDeviceNotice, updateDeviceNotice } from '@/components/Operation/operation'
import axios from 'axios'

// 对话框控制
const dialogVisible = ref(false) // 对话框显示状态
const formRef = ref() // 表单引用
const isEditing = ref(false) // 是否为编辑模式
const editingIndex = ref(-1) // 当前编辑的数据索引
const uploadHeaders = computed(() => {
  return {
    token: sessionStorage.getItem('token') || '' // 每次请求都实时获取
  };
});

// 表单数据（与数据库字段对应）
const form = reactive({
  id: '', // 编辑时传递，添加时为空
  title: '', // 标题
  image: '', // 图片地址
  deviceAvailable: '', // 设备是否可用（前端：可用/不可用 → 后端：1/0）
  timeRange: [], // 显示时间范围（临时存储）
  deviceScope: '', // 应用设备范围
  isDisplay: '', // 是否显示（前端：是/否 → 后端：1/0）
  isDeleted:''
})

// 图片预览地址
const imageUrl = ref("");

// 表单验证规则（与表单字段对应）
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  deviceAvailable: [
    { required: true, message: '请选择设备是否可用', trigger: 'change' }
  ],
  timeRange: [
    { required: true, message: '请选择显示时间范围', trigger: 'change' }
  ],
  isDisplay: [
    { required: true, message: '请选择是否显示', trigger: 'change' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return isEditing.value ? '编辑公告' : '添加公告'
})

// 添加函数
const add = () => {
  isEditing.value = false
  editingIndex.value = -1
  resetForm() // 重置表单
  dialogVisible.value = true
}

// 编辑函数（数据回显，与数据库字段对应）
const handleEdit = (index) => {
  isEditing.value = true
  editingIndex.value = index
  
  const item = tableData.value[index]
  
  // 数据库字段 → 前端表单映射
  form.id = item.id || '' // 编辑时携带id
  form.title = item.title || ''
  form.image = item.image || ''
  // 后端tinyint(1/0) → 前端文字（可用/不可用）
  form.deviceAvailable = item.deviceAvailable === 1 ? '可用' : '不可用'
  // 后端tinyint(1/0) → 前端文字（是/否）
  form.isDisplay = item.isDisplay === 1 ? '是' : '否'
  
  // 图片回显
  imageUrl.value = item.image || ''
  
  // 时间范围回显（后端存储格式："开始时间,结束时间"）
  const timeStr = item.time || ''
  if (timeStr) {
    const timeArray = timeStr.split(',')
    if (timeArray.length === 2 && !isNaN(Date.parse(timeArray[0])) && !isNaN(Date.parse(timeArray[1]))) {
      form.timeRange = [timeArray[0], timeArray[1]]
    } else {
      form.timeRange = []
      ElMessage.warning('时间格式不正确，将清空时间范围')
    }
  } else {
    form.timeRange = []
  }
  
  dialogVisible.value = true
  formRef.value?.clearValidate()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: '',
    title: '',
    image: '',
    deviceAvailable: '',
    timeRange: [],
    isDisplay: '',
    isDeleted:0
  })
  imageUrl.value = ''
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单（添加/编辑统一处理）
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()

    // 构造提交数据（与数据库字段完全对应）
    const submitData = {
      title: form.title,
      image: form.image,
      // 前端文字 → 后端tinyint(1/0)
      deviceAvailable: form.deviceAvailable === '可用' ? 1 : 0,
      // 时间范围拼接为字符串："开始时间,结束时间"
      time: form.timeRange.join(','),
      // 前端文字 → 后端tinyint(1/0)
      isDisplay: form.isDisplay === '是' ? 1 : 0,
      deviceScope: form.deviceScope,
      // 创建时间（后端若自动生成可删除）
      createdAt: new Date().toLocaleString('sv-SE').replace('T', ' ').split('.')[0],
      isDeleted:form.isDeleted
    }
    
    // 编辑模式：添加id字段
    if (isEditing.value) {
      submitData.id = form.id
      submitData.isDeleted=0
    }
    console.log(submitData,111111111);
    
    if (isEditing.value && editingIndex.value !== -1) {
      // 编辑接口：传递包含id的完整数据
      const res = await updateDeviceNotice(submitData)
      console.log(submitData);
      console.log(res);
      
      if (res.code === 200) {
        list()
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error('编辑失败：' + (res.msg || '未知错误'))
      }
    } else {
      // 添加接口：不传递id
      const res = await addDeviceNotice(submitData)
      if (res.code === 200) {
        ElMessage.success('添加成功')
        list() // 重新加载列表
      } else {
        ElMessage.error('添加失败：' + (res.msg || '未知错误'))
      }
    }
    
    handleClose()
  }catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

// 图片上传处理
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    const serverDomain = 'http://106.13.143.56:8080/garbageSys/images';
    const fullImageUrl = serverDomain + response.dataset.filePath;
    imageUrl.value = fullImageUrl;
    form.image = fullImageUrl; // 存储完整图片地址
  } else {
    ElMessage.error('图片上传失败：' + (response.msg || '未知错误'))
  }
}

const beforeAvatarUpload = (rawFile) => {
  const isJPG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  if (!isJPG) {
    ElMessage.error('请上传JPG或PNG格式的图片!')
    return false
  }
  const isLt2M = rawFile.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
};

// 当前激活的按钮
const activeButton = ref('device') // 默认选中设备公告

// 设置激活按钮
const setActiveButton = (buttonName) => {
  activeButton.value = buttonName
}

// 刷新页面函数
const handleRefresh = () => {
  list()
  ElMessage.success('刷新成功')
}

// 表格数据
const tableData = ref([])

// 获取列表数据
function list() {
  try {
    getDeviceNotice().then((res) => {
      if (res.code === 200) {
        tableData.value = res.dataset || []
        console.log('表格数据', tableData.value);
      } else {
        ElMessage.error('获取数据失败：' + (res.msg || '未知错误'))
        tableData.value = []
      }
    })
  } catch (error) {
    console.log('获取数据异常', error);
    ElMessage.error('获取数据失败：网络错误')
    tableData.value = []
  }      
}

// 页面加载时获取列表
onMounted(() => {
  list()
})
</script>
<style lang="less" scoped>
/*头部部分*/
.el-header{
    height: 40px;
    border-bottom: 1px solid rgb(187, 186, 186);
}
.user-info{
  display: flex;
  justify-content: right;
  align-items: center;
}
/*选项部分*/
.option{
    height: 80px;
    border-bottom: 1px solid rgb(187, 186, 186);
    display: flex;
    align-items: center;
    overflow-x: auto; /* 确保横向滚动条正常显示 */
    padding: 0 16px; /* 增加左右内边距，避免边缘紧贴 */
    flex-wrap: nowrap;
    gap: 8px;
}
.el-row{
    height: 100%;
    display: flex;
    justify-content: space-between;
}
.el-col{
    display: flex;
    gap:5px;
    align-items: center;
}
.el-button.is-active {
  background-color: #7ebe85;
  border-color: #76e63a;
  color: #fff;
}
.el-button:hover {
    background-color: #f5f5f5;
    border-color: rgb(138, 138, 138);
    color: black;
}

/*内容部分*/
.content{
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
}
.content-header{
  width: 100%;
  height: 50px;
  border: none;
  display: flex;
  justify-content: right;
  align-items: center;
  gap: 10px;
}
/*添加*/
.add:hover{
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}
/*刷新*/
.refresh:hover{
  background-color: #909399;
  border-color: #909399;
  color: #fff;
}
/*数据表格部分*/
::v-deep .el-table .el-table__header {
  width: 100% !important;
}
::v-deep .el-table .el-table__body {
  width: 100% !important;
}
::v-deep .el-table .el-table__row {
  height: 120px;
}
/*编辑按钮*/
.edit:hover{
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

/* 图片上传样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  p {
    font-size: 12px;
    margin-top: 5px;
  }
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

/* 对话框底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 无图片样式 */
.no-image {
  color: #999;
  font-size: 12px;
}

/* 修复按钮换行问题 */
.option ::v-deep .el-button {
  white-space: nowrap;
}
</style>